package com.system.manager.common.exception;

import com.system.manager.common.entity.Result;
import com.system.manager.common.enums.ErrorCode;
import com.system.manager.modules.authorized.exception.AuthorizationException;
import com.system.manager.modules.projectLibrary.exception.ProjectLibraryException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname SystemGlobalException
 * @Description TODO 系统的全局异常处理器
 * @Date 2021/10/17 11:24
 * @Created by 杨小鹏：【241960695@qq.com】
 */
@Slf4j
@RestControllerAdvice
public class SystemGlobalException {

    /**
     * 处理系统异常
     * @param sysException
     * @return
     */
    @ExceptionHandler(SysException.class)
    public Result resolveSysException(SysException sysException){
        sysException.printStackTrace();
        return Result.error(sysException);
    }


    /**
     * 处理校验参数异常
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result resolveMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        log.info("---->数据校验出现问题");
        exception.printStackTrace();
        // 获取bindingResult类，这个类封装了出现校验失败的数据字段
        BindingResult bindingResult = exception.getBindingResult();

        // 将校验失败的字段封装到一个map集合里面，返回给前端
        Map<String, String> errMsgMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{

            /**
             * fieldError.getField()：获取校验失败的字段名
             * fieldError.getDefaultMessage()： 获取校验失败的信息
             */
            errMsgMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        return Result.error(ErrorCode.FIELD_CHECK_FAILURE, errMsgMap);
    }

    @ExceptionHandler(AuthorizationException.class)
    public Result resolveAuthorizationException(AuthorizationException authException){
        log.info("捕捉到了AuthorizationException");
        authException.printStackTrace();
        return Result.error(authException);
    }

    @ExceptionHandler(ProjectLibraryException.class)
    public Result resolveProjectLibraryException(ProjectLibraryException projectLibraryException){
        log.info("捕捉到了ProjectLibraryException");
        return Result.error(projectLibraryException);
    }
}
